import {AsyncLocalStorage} from 'async_hooks';
import { ValueTransformer } from "typeorm/decorator/options/ValueTransformer";
import { isUndefined, omitBy } from "lodash";

export const globalAsyncLocalStorage = new AsyncLocalStorage<{
  requestId: string,
}>();

export const dateTimeTransformer: ValueTransformer = {
  to: (value: any) => value,
  from: (value: string): number => new Date(value).getTime(),
};

export const numberTransformer: ValueTransformer = {
  to: (value: any) => value,
  from: (value: string) => value !== null ? Number(value) : null,
};

export const moneyTransformer: ValueTransformer = {
  to: (value?: number | null) => value,
  from: (value: string | null): number | null => value !== null ? Number(value) : null,
};


export const getDiffTime = (endTime: string | number, startTime: string | number) => {
  const timestampDiff = new Date(endTime).getTime() - new Date(startTime).getTime(); // 时间差的毫秒数
  let res = '';
  const days = Math.floor(timestampDiff / (24 * 3600 * 1000)); // 计算出相差天数
  if (days) {
    res += `${days}天`;
  }
  const leave1 = timestampDiff % (24 * 3600 * 1000); // 计算出小时数
  const hours = Math.floor(leave1 / (3600 * 1000)); // 计算天数后剩余的毫秒数
  if (hours || days) {
    res += `${hours}时`;
  }
  const leave2 = leave1 % (3600 * 1000); // 计算相差分钟数
  const minutes = Math.floor(leave2 / (60 * 1000)); // 计算小时数后剩余的毫秒数
  if (minutes || hours || days) {
    res += `${minutes}分`;
  }
  const leave3 = leave2 % (60 * 1000); // 计算相差秒数
  const seconds = Math.round(leave3 / 1000); // 计算分钟数后剩余的毫秒数
  if (seconds || minutes || hours || days) {
    res += `${seconds}秒`;
  }
  return res;
}

export const omitUndefined = (obj: any): Record<any, any>=>{
  return omitBy(obj, isUndefined);
}
